﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Data;
using System.Web.UI.WebControls;
using HZ.Supervise.Model;
using HZ.Supervise.Model.Enum;

public partial class TotalDrugs_SortSourceStatistics : BasePage
{

    public TotalDrugs_SortSourceStatistics()
    {
        this.ModuleNo = Module.药品统计分析.ToString();
        this.PageOperateType = OperateType.采购类型统计.ToString();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        QueryControl1.OnQueryClick += new EventHandler(QueryControl1_OnQueryClick);
        if (!IsPostBack)
        {
            ViewState["query"] = URLUtil.GetSuperviseQueryFromURL(Request);
            QueryControl1.BindDataPre((SuperviseQuery)ViewState["query"]);//绑定查询条件的一些数据源 质量层次等
            //BindData();//绑定数据
            QueryControl1.BindSort(gvwInfo);
        }
    }

    void QueryControl1_OnQueryClick(object sender, EventArgs e)
    {
		AspNetPager1.CurrentPageIndex = 1;
    }

    /// <summary>
    /// 绑定符合条件的数据
    /// </summary>
    private void BindData()
    {
        int t = 0;
        HZ.Supervise.IBLL.IExecuteContext ie = HZ.Supervise.BLLFactory.ExecuteContext();
        ie.QueryObject = new HZ.Supervise.Model.QueryObject()
        {
            //分组字段
            GroupField = GroupByField.SortSource,
            //查询条件
            Query = (SuperviseQuery)ViewState["query"],
            //选择分组字段
            GroupSelectField = GroupFields.DistributeAmountTotal | GroupFields.DistributeRate | GroupFields.PurchaseAmountTotal | GroupFields.WareHouseAmountTotal | GroupFields.WareHouseRate | GroupFields.DrugCount,
            //排序字段
            SortField = QueryControl1.SortField == "" ? "SortSource ASC" : QueryControl1.SortField
        };

        System.Data.DataTable dt = ie.ExecutePage(AspNetPager1.CurrentPageIndex, AspNetPager1.PageSize, out t);
        AspNetPager1.RecordCount = t;
        GridViewUtil.AdjustGridView(gvwInfo, dt);
        this.gvwInfo.DataSource = dt;
        this.gvwInfo.DataBind();

        dt.Columns.Add("SortSourceName");
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            dt.Rows[i]["SortSourceName"] = FormatSource(dt.Rows[i]["SortSource"]);
        }

        //设置图表
        setChart(dt);
        //计算中标药所占比例
        GetPercentOfBidAndUnBid(dt);
    }
    /// <summary>
    /// 获取中标药和非中标药的采购比例
    /// </summary>
    /// <param name="dt"></param>
    protected void GetPercentOfBidAndUnBid(System.Data.DataTable dt)
    {
        double bidAmount = (new HZ.Common.ConvertHelper(dt.Compute("SUM(PurchaseAmountTotal)", "SortSource=0")).ToDouble != null) ? new HZ.Common.ConvertHelper(dt.Compute("SUM(PurchaseAmountTotal)", "SortSource=0")).ToDouble.Value : 0.0;
        double unbidAmount = (new HZ.Common.ConvertHelper(dt.Compute("SUM(PurchaseAmountTotal)", "SortSource=1")).ToDouble != null) ? new HZ.Common.ConvertHelper(dt.Compute("SUM(PurchaseAmountTotal)", "SortSource=1")).ToDouble.Value : 0.0;

        if ((bidAmount + unbidAmount) != 0.0)
        {
            this.ltlPercent.Text = (bidAmount / (bidAmount + unbidAmount)).ToString("P2");
            this.ltrPercent1.Text = (unbidAmount / (bidAmount + unbidAmount)).ToString("P2");
        }
        else
        {
            this.ltlPercent.Text = "NA";
            this.ltrPercent1.Text = "NA";
        }

        if (unbidAmount != 0.0)
        {
            this.ltrPercent2.Text = (bidAmount / unbidAmount).ToString("P2");
        }
        else
        {
            this.ltrPercent2.Text = "NA";
        }

    }

    /// <summary>
    /// 设置图表
    /// </summary>
    /// <param name="?"></param>
    private void setChart(System.Data.DataTable dt)
    {
        if (dt.Rows.Count > 0)
        {
            this.ChartControl1.Visible = false;
            HZ.Supervise.Web.WebService.ChartConfig serChart = new HZ.Supervise.Web.WebService.ChartConfig();
            dt.TableName = "采购类型";
            serChart.DataSource = dt;

            if (ShowColumns.ShowColumn == null)
            {
                serChart.XName = "SortSourceName";
                serChart.YNames = "PurchaseAmountTotal";
            }
            else
            {
                string[] _columns = ShowColumns.ShowColumn.GroupFields.ToString().Split(',');
                serChart.XName = "SortSourceName";
                serChart.YNames = _columns[0];
            }

            serChart.ChartTypes = HZ.Supervise.Web.WebService.ChartType.PieChart;

            ChartControl1.webChart = serChart;
            ChartControl1.PageId = Guid.NewGuid().ToString();
            ChartControl1.EntranceChart();
        }
        else
        {
            ChartControl1.Visible = false;
        }
    }
    protected void gvwInfo_RowCommand(object sender, GridViewCommandEventArgs e)
    {

        if (e.CommandName == "DirectByHos")
        {
            if (ShowColumns.ShowColumn == null)
            {
                ShowColumns.ShowColumn = new ShowColumns();
                ShowColumns.ShowColumn.GroupFields = GroupFields.PurchaseCountTotal | GroupFields.PurchaseAmountTotal | GroupFields.WareHouseCountTotal | GroupFields.WareHouseAmountTotal | GroupFields.CountOrder;

            }


            string sessionid = Guid.NewGuid().ToString();
            SuperviseQuery query = (SuperviseQuery)ViewState["query"];
            query.SortSource = int.Parse(e.CommandArgument.ToString());
            query._QueryPrompt = query._QueryPrompt + " " + FormatDrugSource(e.CommandArgument.ToString());
            Session[sessionid] = query;

            string url = System.Configuration.ConfigurationManager.AppSettings["HospitalID"];

            Response.Redirect(string.Format("{0}?sessionid={1}", url, sessionid));
        }

        if (e.CommandName == "DirectByCom")
        {
            if (ShowColumns.ShowColumn == null)
            {
                ShowColumns.ShowColumn = new ShowColumns();
                ShowColumns.ShowColumn.GroupFields = GroupFields.DistributeCountTotal | GroupFields.DistributeRate | GroupFields.PurchaseCountTotal | GroupFields.PurchaseAmountTotal | GroupFields.WareHouseCountTotal | GroupFields.CountOrder;

            }

            string sessionid = Guid.NewGuid().ToString();
            SuperviseQuery query = (SuperviseQuery)ViewState["query"];
            query.SortSource = int.Parse(e.CommandArgument.ToString());
            query._QueryPrompt = query._QueryPrompt + " " + FormatDrugSource(e.CommandArgument.ToString());

            Session[sessionid] = query;
            string url = System.Configuration.ConfigurationManager.AppSettings["CompanyID_PS"];
            Response.Redirect(string.Format("{0}?sessionid={1}", url, sessionid));
        }
        //按药品查看
        if (e.CommandName == "DierectByDrug")
        {
            //设置分组查询字段GroupSelectField
            //if (ShowColumns.ShowColumn == null)
            //{
            //    ShowColumns.ShowColumn = new ShowColumns();
            //    ShowColumns.ShowColumn.GroupFields = GroupFields.DistributeCountTotal | GroupFields.DistributeRate | GroupFields.PurchaseCountTotal | GroupFields.WareHouseCountTotal;
            //}


            string sessionid = Guid.NewGuid().ToString();
            SuperviseQuery query = (SuperviseQuery)ViewState["query"];

            query.SortSource = int.Parse(e.CommandArgument.ToString());
            query._QueryPrompt = query._QueryPrompt + " " + FormatDrugSource(e.CommandArgument.ToString()); ;

            Session[sessionid] = query;
            string url = System.Configuration.ConfigurationManager.AppSettings["ProcureCatalogID"];
            Response.Redirect(string.Format("{0}?sessionid={1}", url, sessionid));
        }

        if (e.CommandName == "DierectByDetail")
        {
            if (ShowColumns.ShowColumn == null)
            {
                ShowColumns.ShowColumn = new ShowColumns();
                ShowColumns.ShowColumn.GroupFields = GroupFields.DistributeCountTotal | GroupFields.DistributeRate | GroupFields.PurchaseCountTotal | GroupFields.PurchaseAmountTotal | GroupFields.WareHouseCountTotal;

            }

            string sessionid = Guid.NewGuid().ToString();
            SuperviseQuery query = (SuperviseQuery)ViewState["query"];

            query.SortSource = int.Parse(e.CommandArgument.ToString());
            query._QueryPrompt = query._QueryPrompt + " " + FormatDrugSource(e.CommandArgument.ToString());

            Session[sessionid] = query;
            string url = System.Configuration.ConfigurationManager.AppSettings["HosComDrugs"];
            Response.Redirect(string.Format("{0}?sessionid={1}", url, sessionid));
        }
    }
    protected void AspNetPager1_PageChanged(object sender, EventArgs e)
    {
		ViewState["query"] = QueryControl1.UpdateQueryFromValue((SuperviseQuery)ViewState["query"]);
		BindData();
    }
    protected void btnExcel_Click(object sender, EventArgs e)
    {
        int t = 0;
        HZ.Supervise.IBLL.IExecuteContext ie = HZ.Supervise.BLLFactory.ExecuteContext();
        ie.QueryObject = new HZ.Supervise.Model.QueryObject()
        {
            GroupField = GroupByField.SortSource,
            Query = (SuperviseQuery)ViewState["query"],
            GroupSelectField = GroupFields.DrugCount | GroupFields.PurchaseAmountTotal | GroupFields.DistributeAmountTotal | GroupFields.DistributeRate | GroupFields.WareHouseAmountTotal | GroupFields.WareHouseRate,
            SortField = QueryControl1.SortField == "" ? "SortSource ASC" : QueryControl1.SortField
        };

        System.Data.DataTable dt = ie.ExecutePage(0, 0, out t);
        dt.Columns.Add("SortSourceName");
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            dt.Rows[i]["SortSourceName"] = FormatSource(dt.Rows[i]["SortSource"]);
        }
        // GridViewUtil.AdjustGridView(gvwInfo, dt);
        ExportFile.Instance.ExportData(dt, gvwInfo, this.Page);
    }
    protected void lbtnSee_Click(object sender, EventArgs e)
    {
        if (this.lbtnSee.Text == "显示图表")
        {
            ChartControl1.Visible = true;
            this.lbtnSee.Text = "隐藏图表";
        }
        else
        {
            ChartControl1.Visible = false;
            this.lbtnSee.Text = "显示图表";
        }
    }
    protected void ddlOther_SelectedIndexChanged(object sender, EventArgs e)
    {
        string stkey = "";
        string sessionid = string.Empty;
        GridViewRow row = (GridViewRow)((Control)sender).Parent.Parent;
        DropDownList ddl = (DropDownList)row.FindControl("ddlOther");
        stkey = ddl.SelectedValue;
        if (stkey != "")
        {
            sessionid = Guid.NewGuid().ToString();
            SuperviseQuery query = (SuperviseQuery)ViewState["query"];
            query.SortSource = Convert.ToInt16(gvwInfo.DataKeys[row.DataItemIndex].Value); //((LinkButton)row.FindControl("lbnHos")).CommandArgument;
            query._QueryPrompt = query._QueryPrompt + " " + FormatDrugSource(gvwInfo.DataKeys[row.DataItemIndex].Value);

            Session[sessionid] = query;
            string url = System.Configuration.ConfigurationManager.AppSettings[stkey];
            Response.Redirect(string.Format("{0}?sessionid={1}", url, sessionid));
        }
    }


    /// <summary>
    /// 格式化采购类型
    /// </summary>
    /// <param name="obj"></param>
    /// <returns></returns>
    public static string FormatSource(object obj)
    {
        string status = "未知";
        if (obj != null)
        {
            switch (Convert.ToInt16(obj))
            {
                case 0: status = "中标药";
                    break;
                case 1: status = "重点监控";
                    break;
                case 2: status = "备案药品";
                    break;
                case 3: status = "非中标";
                    break;
            }
        }
        return status;
    }

    /// <summary>
    /// 格式化采购类型
    /// </summary>
    /// <param name="obj"></param>
    /// <returns></returns>
    public static string FormatDrugSource(object obj)
    {
        string status = "未知";
        if (obj != null)
        {
            switch (Convert.ToInt16(obj))
            {
                case 0: status = "<font color=black>中标药</font>";
                    break;
                case 1: status = "<font color=red>重点监控</font>";
                    break;
                case 2: status = "<font color=blue>备案药品</font>";
                    break;
                case 3: status = "<font color=gray><i>非中标</i></font>";
                    break;
            }
        }
        return status;
    }

}
